from channels.generic.websocket import AsyncWebsocketConsumer
from soc.setup import *
import asyncio
from urllib.parse import parse_qsl
from django.core.cache import cache


class ChatConsumer(AsyncWebsocketConsumer):

    def __init__(self, *args, **kwargs):
        self.group_name = "Room-1-2"
        super().__init__(*args, **kwargs)

    async def connect(self):
        query_string = self.scope['query_string'].decode()
        params = dict(parse_qsl(query_string))
        print(params)
        await self.accept()
        print(self.channel_layer)
        await self.channel_layer.group_add(self.group_name, self.channel_name)

    async def disconnect(self, close_code):
        pass

    async def receive(self, text_data):
        await self.channel_layer.group_send(self.group_name, {
            "type": "chat.message",
            "message": text_data
        })

    async def chat_message(self, event):
        await self.send(text_data=event["message"])


class LinkConsumer(AsyncWebsocketConsumer):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    async def connect(self):
        x = 0
        await self.accept()
        print("连接成功")
        while True:
            await asyncio.sleep(1/2)
            print(cache.get("position"))
            x = x + 0.01
            await self.send(str(x))

    async def disconnect(self, close_code):
        print("断开链接")
        pass

    async def receive(self, text_data):
        print("收到消息")
        pass
